package com.admin.controller;

import ch.qos.logback.core.net.SyslogOutputStream;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import com.admin.entity.Admin;
import com.admin.entity.Fileinfo;
import com.admin.entity.Station;
import com.admin.entity.Theme;
import com.admin.service.IStationService;
import com.admin.service.IThemeService;
import com.admin.service.impl.DragService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.OssUpload;
import com.bean.ApiClass;
import com.util.MD5Util;
import com.util.StringUtil;
import org.apache.tomcat.jni.FileInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 文件上传下载
 *
 * @author wangfei
 * 图片上传时间太长的解决方案（进行md5对比，相同的图片不上传）
 */
@Controller
public class UploadController {




    private String separator = File.separator;

    @Autowired
    private DragService service;

    @Value("${upload.dir}")
    private String upload;

    @Autowired
    private IThemeService themeService;

    @Autowired
    private IStationService stationService;

    @Value("${SERVER}")
    private String SERVER;

    @Value("${apk.ppt.url}")
    private String pptURL;

    @Autowired
    private OssUpload ossUpload;


    public ApiClass image(Integer width, Integer height) {
        return null;
    }

    /**
     * 计算MD5值
     * @param fileName
     * @return
     */
    private Map md5(String fileName) throws IOException {
//        System.out.println(fileName);

        ApplicationHome home = new ApplicationHome(getClass());
        File sysfile = home.getSource();
        String ROOT_PATH = sysfile.getParentFile().toString();


        int index = fileName.indexOf("?");
        if (index > -1) {
            fileName = fileName.substring(0, index);
        }
        String tempFile = fileName;
        if (fileName.startsWith("./")) {
            tempFile = fileName.substring(2);
        }
        String newFileName = upload + tempFile;
        File file = new File(newFileName);
        if (file.exists() == false) {
//            newFileName = ROOT_PATH + "/classes/static" + (tempFile.startsWith("/") ? "" : "/") + tempFile;
//            if(System.getProperty("os.name").toLowerCase().contains("windows")) {
//                newFileName = newFileName.replaceAll("/" , "\\\\") ;
//            }

//            System.out.println(newFileName);
//            System.out.println("static/img" + newFileName.substring(newFileName.lastIndexOf("/")));
            ClassPathResource classPathResource = new ClassPathResource("static/img" + newFileName.substring(newFileName.lastIndexOf("/"))) ;

            String md5 = MD5Util.md5sum(classPathResource.getInputStream());
            Map map = new HashMap();
            map.put("name", fileName);
            map.put("md5", md5);
            return map;
        }

        String md5 = MD5Util.md5sum(newFileName);
        Map map = new HashMap();
        map.put("name", fileName);
        map.put("md5", md5);
        return map;
    }

    /**
     * 界面文件上传
     *
     * @param language 界面语言
     * @param code     界面代码
     * @return 返回部分不满足分辨率的图片
     * @throws NoSuchAlgorithmException
     */
    @RequestMapping("/pageUpload")
    @ResponseBody
    public ApiClass page(String language, String id, String code, HttpServletRequest request) throws NoSuchAlgorithmException, IOException {
//        System.out.println(code);
        ApiClass api = new ApiClass();
        Map<String, Object> map = null;
        //判断语言参数是否为空
        if (language == null || language.equals("")) {
            language="CN";
        }
        if (id != null) {
            try {
                Integer.parseInt(id);
            } catch (Exception e) {
                api.setCode(500);
                api.setMsg("id异常");
                api.setData("");
                return api;
            }
        } else {
            api.setCode(500);
            api.setMsg("id异常");
            api.setData("");
            return api;
        }
        //判断编辑生成的json是否为空
        if (code == null || code.equals("")) {
            api.setCode(500);
            api.setMsg("界面数据异常");
            api.setData("");
            return api;
        } else {

            map = JSONObject.parseObject(code, Map.class);
            //将所有图片计算md5并存数据库
            //图片存储路径
            String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String path = upload + "screen" + separator + "upload" + separator + date;
            //找出背景图片
            String bgBase64 = (String) ((Map) ((Map) map.get("panel")).get("BG")).get("img");

            if (bgBase64 != null && bgBase64.startsWith("data:image/")) {

                if (!new File(path).exists()) {

                    new File(path).mkdirs();
                }
                String suffix = bgBase64.substring(11, bgBase64.indexOf(";"));
                String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                //将md5图片转换成字节数组
                //byte[] data = Base64.decode(bgBase64.substring(bgBase64.indexOf(",")+1)) ;
                MessageDigest md5Digest = MessageDigest.getInstance("md5");
                //对图片进行md5计算
                byte[] digest = md5Digest.digest(bgBase64.getBytes());
                String md5 = HexUtil.encodeHexStr(digest);

                if (!service.isExist(md5)) {
                    Fileinfo pictrul = new Fileinfo();
                    pictrul.setMd5(md5);
                    pictrul.setType("img");
                    pictrul.setUrl("./screen/upload/" + date + "/" + name);
                    Fileinfo p = service.addImg(pictrul);
                    File file = new File(path + separator + name);
                    Base64.decodeToFile(bgBase64.substring(bgBase64.indexOf(",") + 1), file);
                    //上传到OSS
                    ossUpload.upload("/screen/upload/" + date + "/" + name, file);

                    ((Map) ((Map) map.get("panel")).get("BG")).put("img", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                } else {
                    Fileinfo p = service.getImg(md5);
                    ((Map) ((Map) map.get("panel")).get("BG")).put("img", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                }
            } else if (bgBase64 != null) {
                Map<String, String> resultMap = md5(bgBase64);
                String md5 = resultMap.get("md5");
                String name = resultMap.get("name");
                ((Map) ((Map) map.get("panel")).get("BG")).put("img", name + "?md5=" + md5);
            }
            //1.找出logo中的图片
            String logoBase64 = (String) ((Map) ((Map) map.get("panel")).get("VUELOGO")).get("img");
            if (logoBase64 != null && logoBase64.startsWith("data:image/")) {
                if (!new File(path).exists()) {
                    new File(path).mkdirs();
                }
                String suffix = logoBase64.substring(11, logoBase64.indexOf(";"));
                String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                //将md5图片转换成字节数组
                //byte[] data = Base64.decode(logoBase64.substring(logoBase64.indexOf(",")+1)) ;
                MessageDigest md5Digest = MessageDigest.getInstance("md5");
                //对图片进行md5计算
                byte[] digest = md5Digest.digest(logoBase64.getBytes());
                String md5 = HexUtil.encodeHexStr(digest);
                if (!service.isExist(md5)) {
                    Fileinfo pictrul = new Fileinfo();
                    pictrul.setMd5(md5);
                    pictrul.setType("img");
                    pictrul.setUrl("./screen/upload/" + date + "/" + name);
                    Fileinfo p = service.addImg(pictrul);
                    File file = new File(path + separator + name);
                    Base64.decodeToFile(logoBase64.substring(logoBase64.indexOf(",") + 1), file);
                    ossUpload.upload("/screen/upload/" + date + "/" + name, file);
                    ((Map) ((Map) map.get("panel")).get("VUELOGO")).put("img", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                } else {
                    Fileinfo p = service.getImg(md5);
                    ((Map) ((Map) map.get("panel")).get("VUELOGO")).put("img", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                }
            } else if (logoBase64 != null) {
                Map<String, String> resultMap = md5(logoBase64);
                String md5 = resultMap.get("md5");
                String name = resultMap.get("name");
                ((Map) ((Map) map.get("panel")).get("VUELOGO")).put("img", name + "?md5=" + md5);
            }

            String leftBase64 = (String) ((Map) ((Map) map.get("panel")).get("VUELEFTPANEL")).get("img");
            if (leftBase64 != null && leftBase64.startsWith("data:image/")) {
                if (!new File(path).exists()) {
                    new File(path).mkdirs();
                }
                String suffix = leftBase64.substring(11, leftBase64.indexOf(";"));
                String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                //将md5图片转换成字节数组
                //byte[] data = Base64.decode(logoBase64.substring(logoBase64.indexOf(",")+1)) ;
                MessageDigest md5Digest = MessageDigest.getInstance("md5");
                //对图片进行md5计算
                byte[] digest = md5Digest.digest(leftBase64.getBytes());
                String md5 = HexUtil.encodeHexStr(digest);
                if (!service.isExist(md5)) {
                    Fileinfo pictrul = new Fileinfo();
                    pictrul.setMd5(md5);
                    pictrul.setType("img");
                    pictrul.setUrl("./screen/upload/" + date + "/" + name);
                    Fileinfo p = service.addImg(pictrul);
                    File file = new File(path + separator + name);
                    Base64.decodeToFile(leftBase64.substring(leftBase64.indexOf(",") + 1), file);
                    ossUpload.upload("/screen/upload/" + date + "/" + name, file);
                    ((Map) ((Map) map.get("panel")).get("VUELEFTPANEL")).put("img", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                } else {
                    Fileinfo p = service.getImg(md5);
                    ((Map) ((Map) map.get("panel")).get("VUELEFTPANEL")).put("img", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                }
            } else if (leftBase64 != null) {
                Map<String, String> resultMap = md5(leftBase64);
                String md5 = resultMap.get("md5");
                String name = resultMap.get("name");
                ((Map) ((Map) map.get("panel")).get("VUELEFTPANEL")).put("img", name + "?md5=" + md5);
            }

            //关于我们图片
            String aboutImg = (String) ((Map) ((Map) map.get("panel")).get("ABOUT")).get("img");
            if (aboutImg != null && aboutImg.startsWith("data:image/")) {
                if (!new File(path).exists()) {
                    new File(path).mkdirs();
                }
                String suffix = aboutImg.substring(11, aboutImg.indexOf(";"));
                String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                //将md5图片转换成字节数组
                //byte[] data = Base64.decode(logoBase64.substring(logoBase64.indexOf(",")+1)) ;
                MessageDigest md5Digest = MessageDigest.getInstance("md5");
                //对图片进行md5计算
                byte[] digest = md5Digest.digest(aboutImg.getBytes());
                String md5 = HexUtil.encodeHexStr(digest);
                if (!service.isExist(md5)) {
                    Fileinfo pictrul = new Fileinfo();
                    pictrul.setMd5(md5);
                    pictrul.setType("img");
                    pictrul.setUrl("./screen/upload/" + date + "/" + name);
                    Fileinfo p = service.addImg(pictrul);
                    File file = new File(path + separator + name);
                    Base64.decodeToFile(aboutImg.substring(aboutImg.indexOf(",") + 1), file);
                    ossUpload.upload("/screen/upload/" + date + "/" + name, file);
                    ((Map) ((Map) map.get("panel")).get("ABOUT")).put("img", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                } else {
                    Fileinfo p = service.getImg(md5);
                    ((Map) ((Map) map.get("panel")).get("ABOUT")).put("img", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                }
            } else if (aboutImg != null) {
                Map<String, String> resultMap = md5(aboutImg);
                String md5 = resultMap.get("md5");
                String name = resultMap.get("name");
                ((Map) ((Map) map.get("panel")).get("ABOUT")).put("img", name + "?md5=" + md5);
            }
            //2.找出内容组件与导航栏中的图片
            List bars = (List) ((Map) ((Map) map.get("panel")).get("MAIN")).get("data");
            for (Object o : bars) {
                String barBase64 = (String) ((Map) o).get("img");
                if (barBase64 != null && barBase64.startsWith("data:image/")) {
                    if (!new File(path).exists()) {
                        new File(path).mkdirs();
                    }
                    String suffix = barBase64.substring(11, barBase64.indexOf(";"));
                    String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                    //将md5图片转换成字节数组
                    //byte[] data = Base64.decode(barBase64.substring(barBase64.indexOf(",")+1)) ;
                    MessageDigest md5Digest = MessageDigest.getInstance("md5");
                    //对图片进行md5计算
                    byte[] digest = md5Digest.digest(barBase64.getBytes());
                    String md5 = HexUtil.encodeHexStr(digest);
                    if (!service.isExist(md5)) {
                        Fileinfo pictrul = new Fileinfo();
                        pictrul.setMd5(md5);
                        pictrul.setType("img");
                        pictrul.setUrl("./screen/upload/" + date + "/" + name);
                        Fileinfo p = service.addImg(pictrul);
                        File file = new File(path + separator + name);
                        Base64.decodeToFile(barBase64.substring(barBase64.indexOf(",") + 1), file);
                        ossUpload.upload("/screen/upload/" + date + "/" + name, file);
                        ((Map) o).put("img", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                    } else {
                        Fileinfo p = service.getImg(md5);
                        ((Map) o).put("img", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                    }
                } else if (barBase64 != null)  //内置
                {
                    Map<String, String> resultMap = md5(barBase64);
                    String md5 = resultMap.get("md5");
                    String name = resultMap.get("name");
                    ((Map) o).put("img", name + "?md5=" + md5);
                }

                String barSelectedBase64 = (String) ((Map) o).get("selectedImg");
                if (barSelectedBase64 != null && barSelectedBase64.startsWith("data:image/")) {
                    if (!new File(path).exists()) {
                        new File(path).mkdirs();
                    }
                    String suffix = barSelectedBase64.substring(11, barSelectedBase64.indexOf(";"));
                    String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                    //将md5图片转换成字节数组
                    //byte[] data = Base64.decode(barBase64.substring(barBase64.indexOf(",")+1)) ;
                    MessageDigest md5Digest = MessageDigest.getInstance("md5");
                    //对图片进行md5计算
                    byte[] digest = md5Digest.digest(barSelectedBase64.getBytes());
                    String md5 = HexUtil.encodeHexStr(digest);
                    if (!service.isExist(md5)) {
                        Fileinfo pictrul = new Fileinfo();
                        pictrul.setMd5(md5);
                        pictrul.setType("img");
                        pictrul.setUrl("./screen/upload/" + date + "/" + name);
                        Fileinfo p = service.addImg(pictrul);
                        File file = new File(path + separator + name);
                        Base64.decodeToFile(barSelectedBase64.substring(barSelectedBase64.indexOf(",") + 1), file);
                        ossUpload.upload("/screen/upload/" + date + "/" + name, file);
                        ((Map) o).put("selectedImg", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                    } else {
                        Fileinfo p = service.getImg(md5);
                        ((Map) o).put("selectedImg", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                    }
                } else if (barSelectedBase64 != null)  //内置
                {
                    Map<String, String> resultMap = md5(barSelectedBase64);
                    String md5 = resultMap.get("md5");
                    String name = resultMap.get("name");
                    ((Map) o).put("selectedImg", name + "?md5=" + md5);
                }


                if(((Map) o).get("subMenu") != null) {
                    List submenus = (List) ((Map) o).get("subMenu") ;

                    for(Object obj : submenus) {
                        Map item = (Map) obj ;
                        if(item.get("ppt") != null) {
                            List ppts = (List) item.get("ppt") ;
                            int idx = 0 ;
                            for(Object obj1 : ppts) {
                                Map<String , String> m = (Map) obj1 ;
                                if("img".equals(m.get("type"))) {
                                    String base64 = m.get("value") ;
                                    if (base64 != null && base64.startsWith("data:image/")) {
                                        if (!new File(path).exists()) {
                                            new File(path).mkdirs();
                                        }
                                        String suffix = base64.substring(11, base64.indexOf(";"));
                                        String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                                        //将md5图片转换成字节数组
                                        //byte[] data = Base64.decode(barBase64.substring(barBase64.indexOf(",")+1)) ;
                                        MessageDigest md5Digest = MessageDigest.getInstance("md5");
                                        //对图片进行md5计算
                                        byte[] digest = md5Digest.digest(base64.getBytes());
                                        String md5 = HexUtil.encodeHexStr(digest);
                                        if (!service.isExist(md5)) {
                                            Fileinfo pictrul = new Fileinfo();
                                            pictrul.setMd5(md5);
                                            pictrul.setType("img");
                                            pictrul.setUrl("./screen/upload/" + date + "/" + name);
                                            Fileinfo p = service.addImg(pictrul);
                                            File file = new File(path + separator + name);
                                            Base64.decodeToFile(base64.substring(base64.indexOf(",") + 1), file);
                                            ossUpload.upload("/screen/upload/" + date + "/" + name, file);
                                            m.put("value", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                                        } else {
                                            Fileinfo p = service.getImg(md5);
                                            m.put("value", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                                        }
                                    } else if (base64 != null)  //内置
                                    {
                                        Map<String, String> resultMap = md5(base64);
                                        String md5 = resultMap.get("md5");
                                        String name = resultMap.get("name");
                                        m.put("value", name + "?md5=" + md5);
                                    }
                                    ppts.set(idx , m) ;
                                    System.out.println(m);
                                    idx ++ ;
                                }
                            }
                        }
                    }
                }

                //找出内容组件中的图片
                if(((Map) ((Map) o).get("data")).get("info") instanceof List) {
                    List contents = (List) ((Map) ((Map) o).get("data")).get("info");
                    if(contents != null) {
                        for (Object m : contents) {
                            parseContent(m , path , date) ;
                        }
                    }
                }else{
                    Object m = ((Map) ((Map) o).get("data")).get("info") ;
                    parseContent(m , path , date) ;
                }


            }

            List<String> aboutPpt = (List<String>) ((Map) ((Map) map.get("panel")).get("ABOUT")).get("ppt");
            if (aboutPpt != null) {
                for (int i = 0; i < aboutPpt.size(); i++) {
                    Object pptObj = aboutPpt.get(i);
                    String pptString = null;
                    if (pptObj!=null){
                        if (pptObj.getClass()==String.class){
                            pptString = (String)pptObj;
                        }
                        else if (pptObj.getClass()== JSONObject.class) {
                             JSONObject  jsonObject = (JSONObject)pptObj;
                             String type = jsonObject.getString("type");
                             if ("img".equals(type)){
                                 pptString = jsonObject.getString("value");
                             }
                        }
                    }
                    if (pptString != null && pptString.startsWith("data:image/")) {
                        if (!new File(path).exists()) {
                            new File(path).mkdirs();
                        }
                        String suffix = pptString.substring(11, pptString.indexOf(";"));
                        String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                        //将md5图片转换成字节数组
                        //byte[] data = Base64.decode(imgs.get(i).substring(imgs.get(i).indexOf(",")+1)) ;
                        MessageDigest md5Digest = MessageDigest.getInstance("md5");
                        //对图片进行md5计算
                        byte[] digest = md5Digest.digest(pptString.getBytes());
                        String md5 = HexUtil.encodeHexStr(digest);
                        if (!service.isExist(md5)) {
                            Fileinfo pictrul = new Fileinfo();
                            pictrul.setMd5(md5);
                            pictrul.setUrl("./screen/upload/" + date + "/" + name);
                            pictrul.setType("img");
                            Fileinfo p = service.addImg(pictrul);
                            Base64.decodeToFile(pptString.substring(pptString.indexOf(",") + 1), new File(path + separator + name));
                            aboutPpt.set(i, p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                            File file = new File(path + separator + name);
                            ossUpload.upload("/screen/upload/" + date + "/" + name, file);
                        } else {
                            Fileinfo p = service.getImg(md5);
                            aboutPpt.set(i, p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                        }
                    } else if (pptString != null) {
                        Map<String, String> resultMap = md5(pptString);
                        String md5 = resultMap.get("md5");
                        String name = resultMap.get("name");
                        aboutPpt.set(i, name + "?md5=" + md5);
                    }
                }
            }

            //没有导航栏时要额外处理一下
            List<Object> l = (List<Object>) ((Map) ((Map) map.get("panel")).get("MAIN")).get("data");
            boolean item = (Boolean) ((Map) ((Map) map.get("panel")).get("MAIN")).get("bar");
            if (!item) {
                int len = l.size() - 1;
                for (int i = 0; i < len; i++) {
                    l.remove(l.size() - 1);
                }
            }
            //写文件
            /*File dir = new File(upload + "screen" + separator + id + separator + language);
            if (!dir.exists()) {
                dir.mkdirs();
            }*/

            //-----------------------------------------------------------------------------------------
            String json = (map != null ? JSONObject.toJSONString(map) : code);
            json = json.replaceAll("\n","\\n");
            json = json.replaceAll("\r","\\r");

            Theme theme = themeService.getById(id);
            String dbCode = "fun_id" + "('" + json + "')";
            Admin admin = (Admin) request.getSession().getAttribute("admin");

            if (admin != null && admin.getAdminParent() != null && admin.getAdminParent() == 0) { //如果是管理员登录，这里要判断
                switch (language){
                    case "CN":
                        theme.setThemeAuditPcAudited(dbCode);
                        theme.setThemeShenheStatus("审核通过");
                        break;
                    case "EN":
                        theme.setEnglishPcYes(dbCode);
                        theme.setThemeShenheStatus("审核通过");
                        break;
                }

            } else {
                Station station = (Station) request.getSession().getAttribute("station");
                if (admin == null && station == null) {
                    api.setCode(500);
                    api.setMsg("登录失效");
                    api.setData("");
                    return api;
                }
                theme.setThemeShenheStatus("未审核");
            }

            switch (language){
                case "CN":
                    theme.setThemeAuditPcUnaudited(dbCode);
                    break;
                case "EN":
                    theme.setEnglishPcNo(dbCode);
                    break;
            }


            //theme.setThemeShenheStatus("审核通过");
            themeService.saveOrUpdate(theme);
            //-----------------------------------------------------------------------------------------

            /*
            File file = new File(upload + "screen" + separator + id + separator + language + separator + "screen.json");
            OutputStreamWriter writer = null;
            try {
                writer = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
                writer.write("fun_id" + "('" + json + "')");
            } catch (IOException e) {
                api.setCode(500);
                api.setMsg("存储失败");
                api.setData("");
                return api;
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }*/

            ApiClass saveCode = saveAsAndroidCode(id, map, language, request);

            api.setCode(200);
            api.setMsg("上传成功");
            api.setData("");
            return api;
        }
    }

    void parseContent(Object m , String path , String date) throws NoSuchAlgorithmException, IOException {
        String video = (String) ((Map) m).get("video");
        if (video != null) {
            Map<String, String> mapVideo = md5(video);
            String md5 = mapVideo.get("md5");
            String name = mapVideo.get("name");
            ((Map) m).put("video", name + "?md5=" + md5);
        }

        List<String> viedos = (List)((Map)m).get("videos");

        if (viedos!=null && viedos.size()>0)
        {
            List   listViedos = new ArrayList();
            for (String v:viedos)
            {
                Map<String, String> mapVideo = md5(v);
                String md5 = mapVideo.get("md5");
                String name = mapVideo.get("name");
                listViedos.add(name + "?md5=" + md5);
            }
            ((Map) m).put("videos", listViedos);
        }


        List<String> imgs = (List<String>) ((Map) m).get("imgs");
        for (int i = 0; i < imgs.size(); i++) {

            if (imgs.get(i) != null && imgs.get(i).startsWith("data:image/")) {
                if (!new File(path).exists()) {
                    new File(path).mkdirs();
                }
                String suffix = imgs.get(i).substring(11, imgs.get(i).indexOf(";"));
                String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                //将md5图片转换成字节数组
                //byte[] data = Base64.decode(imgs.get(i).substring(imgs.get(i).indexOf(",")+1)) ;
                MessageDigest md5Digest = MessageDigest.getInstance("md5");
                //对图片进行md5计算
                byte[] digest = md5Digest.digest(imgs.get(i).getBytes());
                String md5 = HexUtil.encodeHexStr(digest);
                if (!service.isExist(md5)) {

                    Fileinfo pictrul = new Fileinfo();
                    pictrul.setMd5(md5);
                    pictrul.setUrl("./screen/upload/" + date + "/" + name);
                    pictrul.setType("img");
                    Fileinfo p = service.addImg(pictrul);

                    File file = new File(path + separator + name);
                    Base64.decodeToFile(imgs.get(i).substring(imgs.get(i).indexOf(",") + 1), new File(path + separator + name));
                    ossUpload.upload("/screen/upload/" + date + "/" + name, file);


                    imgs.set(i, p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                } else {
                    Fileinfo p = service.getImg(md5);
                    imgs.set(i, p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                }
            } else if (imgs.get(i) != null) {
                Map<String, String> resultMap = md5(imgs.get(i));
                String md5 = resultMap.get("md5");
                String name = resultMap.get("name");
                imgs.set(i, name + "?md5=" + md5);
            }
        }

        // 子菜单ppt

        if (((Map) m).get("apk") != null && !"".equals(((Map) m).get("apk"))) {

            //System.out.println((List<String>) ((Map) m).get("ppt"));
            if (((Map) m).get("packageName") != null && "com.desktop.ppt".equals(((Map) m).get("packageName"))) {

                try {
                    //兼容之前
                    List<String> imgsPpt = (List<String>) ((Map) m).get("ppt");
                    for (int i = 0; i < imgsPpt.size(); i++) {
                        if (imgsPpt.get(i) != null && imgsPpt.get(i).startsWith("data:image/")) {
                            if (!new File(path).exists()) {
                                new File(path).mkdirs();
                            }
                            String suffix = imgsPpt.get(i).substring(11, imgsPpt.get(i).indexOf(";"));
                            String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                            //将md5图片转换成字节数组
                            //byte[] data = Base64.decode(imgs.get(i).substring(imgs.get(i).indexOf(",")+1)) ;
                            MessageDigest md5Digest = MessageDigest.getInstance("md5");
                            //对图片进行md5计算
                            byte[] digest = md5Digest.digest(imgsPpt.get(i).getBytes());
                            String md5 = HexUtil.encodeHexStr(digest);
                            if (!service.isExist(md5)) {
                                Fileinfo pictrul = new Fileinfo();
                                pictrul.setMd5(md5);
                                pictrul.setUrl("./screen/upload/" + date + "/" + name);
                                pictrul.setType("img");
                                Fileinfo p = service.addImg(pictrul);

                                File file = new File(path + separator + name);
                                Base64.decodeToFile(imgsPpt.get(i).substring(imgsPpt.get(i).indexOf(",") + 1), file);
                                ossUpload.upload("/screen/upload/" + date + "/" + name, file);
                                imgsPpt.set(i, p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                            } else {
                                Fileinfo p = service.getImg(md5);
                                imgsPpt.set(i, p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                            }
                        } else if (imgsPpt.get(i) != null) {
                            Map<String, String> resultMap = md5(imgsPpt.get(i));
                            String md5 = resultMap.get("md5");
                            String name = resultMap.get("name");
                            imgsPpt.set(i, name + "?md5=" + md5);
                        }
                    }
                }catch (Exception e){
                    List<JSONObject> imgsPpt = (List<JSONObject>) ((Map) m).get("ppt");
                    if (imgsPpt!=null)
                        for (int i = 0; i < imgsPpt.size(); i++) {
                            JSONObject pptObject = imgsPpt.get(i);
                            //[{"type":"video","value":"./video/2020-07-27/69e2e0ef6ba14aa1aee03b26044162ec.mp4"}]
                            String type = pptObject.getString("type");
                            String value = pptObject.getString("value");
                            if (value!=null && value.startsWith("data:image/")) {
                                if (!new File(path).exists()) {
                                    new File(path).mkdirs();
                                }
                                String suffix = value.substring(11, value.indexOf(";"));
                                String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                                //将md5图片转换成字节数组
                                //byte[] data = Base64.decode(imgs.get(i).substring(imgs.get(i).indexOf(",")+1)) ;
                                MessageDigest md5Digest = MessageDigest.getInstance("md5");
                                //对图片进行md5计算
                                byte[] digest = md5Digest.digest(value.getBytes());
                                String md5 = HexUtil.encodeHexStr(digest);
                                if (!service.isExist(md5)) {
                                    Fileinfo pictrul = new Fileinfo();
                                    pictrul.setMd5(md5);
                                    pictrul.setUrl("./screen/upload/" + date + "/" + name);
                                    pictrul.setType("img");
                                    Fileinfo p = service.addImg(pictrul);

                                    File file = new File(path + separator + name);
                                    Base64.decodeToFile(value.substring(value.indexOf(",") + 1), file);
                                    ossUpload.upload("/screen/upload/" + date + "/" + name, file);
                                    pptObject.put("value", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                                } else {
                                    Fileinfo p = service.getImg(md5);
                                    pptObject.put("value", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                                }
                            } else if (imgsPpt.get(i) != null) {
                                Map<String, String> resultMap = md5(value);
                                String md5 = resultMap.get("md5");
                                String name = resultMap.get("name");
                                pptObject.put("value", name + "?md5=" + md5);
                            }
                        }
                }

            } else if (((Map) m).get("packageName") != null && "com.iptv.jishi".equals(((Map) m).get("packageName"))) {
                if ((Map) ((Map) m).get("technician") != null) {
                    String bg = (String) ((Map) ((Map) ((Map) m).get("technician")).get("bg")).get("img");
                    if (bg != null && bg.startsWith("data:image/")) {
                        if (!new File(path).exists()) {
                            new File(path).mkdirs();
                        }
                        String suffix = bg.substring(11, bg.indexOf(";"));
                        String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                        //将md5图片转换成字节数组
                        //byte[] data = Base64.decode(logoBase64.substring(logoBase64.indexOf(",")+1)) ;
                        MessageDigest md5Digest = MessageDigest.getInstance("md5");
                        //对图片进行md5计算
                        byte[] digest = md5Digest.digest(bg.getBytes());
                        String md5 = HexUtil.encodeHexStr(digest);
                        if (!service.isExist(md5)) {
                            Fileinfo pictrul = new Fileinfo();
                            pictrul.setMd5(md5);
                            pictrul.setType("img");
                            pictrul.setUrl("./screen/upload/" + date + "/" + name);
                            Fileinfo p = service.addImg(pictrul);
                            Base64.decodeToFile(bg.substring(bg.indexOf(",") + 1), new File(path + separator + name));
                            ((Map) ((Map) ((Map) m).get("technician")).get("bg")).put("img", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                            ossUpload.upload("/screen/upload/" + date + "/" + name,new File(path + separator + name));
                        } else {
                            Fileinfo p = service.getImg(md5);
                            ((Map) ((Map) ((Map) m).get("technician")).get("bg")).put("img", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                        }
                    } else if (bg != null) {
                        Map<String, String> resultMap = md5(bg);
                        String md5 = resultMap.get("md5");
                        String name = resultMap.get("name");
                        ((Map) ((Map) ((Map) m).get("technician")).get("bg")).put("img", name + "?md5=" + md5);
                    }
                    List items = (List) ((Map) ((Map) m).get("technician")).get("list");
                    for (int j = 0; j < items.size(); j++) {
                        String img = (String) ((Map) items.get(j)).get("img");
                        if (img != null && img.startsWith("data:image/")) {
                            if (!new File(path).exists()) {
                                new File(path).mkdirs();
                            }
                            String suffix = img.substring(11, img.indexOf(";"));
                            String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                            //将md5图片转换成字节数组
                            //byte[] data = Base64.decode(logoBase64.substring(logoBase64.indexOf(",")+1)) ;
                            MessageDigest md5Digest = MessageDigest.getInstance("md5");
                            //对图片进行md5计算
                            byte[] digest = md5Digest.digest(img.getBytes());
                            String md5 = HexUtil.encodeHexStr(digest);
                            if (!service.isExist(md5)) {
                                Fileinfo pictrul = new Fileinfo();
                                pictrul.setMd5(md5);
                                pictrul.setType("img");
                                pictrul.setUrl("./screen/upload/" + date + "/" + name);
                                Fileinfo p = service.addImg(pictrul);
                                Base64.decodeToFile(img.substring(img.indexOf(",") + 1), new File(path + separator + name));
                                ((Map) items.get(j)).put("img", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                                ossUpload.upload("/screen/upload/" + date + "/" + name,new File(path + separator + name));
                            } else {
                                Fileinfo p = service.getImg(md5);
                                ((Map) items.get(j)).put("img", p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                            }
                        } else if (img != null) {
                            Map<String, String> resultMap = md5(img);
                            String md5 = resultMap.get("md5");
                            String name = resultMap.get("name");
                            ((Map) items.get(j)).put("img", name + "?md5=" + md5);
                        }
                        List<String> imgsPpt = (List<String>) ((Map) items.get(j)).get("ppt");
                        if (imgsPpt != null) {
                            for (int i = 0; i < imgsPpt.size(); i++) {
                                if (imgsPpt.get(i) != null && imgsPpt.get(i).startsWith("data:image/")) {
                                    if (!new File(path).exists()) {
                                        new File(path).mkdirs();
                                    }
                                    String suffix = imgsPpt.get(i).substring(11, imgsPpt.get(i).indexOf(";"));
                                    String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                                    //将md5图片转换成字节数组
                                    //byte[] data = Base64.decode(imgs.get(i).substring(imgs.get(i).indexOf(",")+1)) ;
                                    MessageDigest md5Digest = MessageDigest.getInstance("md5");
                                    //对图片进行md5计算
                                    byte[] digest = md5Digest.digest(imgsPpt.get(i).getBytes());
                                    String md5 = HexUtil.encodeHexStr(digest);
                                    if (!service.isExist(md5)) {
                                        Fileinfo pictrul = new Fileinfo();
                                        pictrul.setMd5(md5);
                                        pictrul.setUrl("./screen/upload/" + date + "/" + name);
                                        pictrul.setType("img");
                                        Fileinfo p = service.addImg(pictrul);
                                        Base64.decodeToFile(imgsPpt.get(i).substring(imgsPpt.get(i).indexOf(",") + 1), new File(path + separator + name));
                                        imgsPpt.set(i, p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                                        ossUpload.upload("/screen/upload/" + date + "/" + name,new File(path + separator + name));
                                    } else {
                                        Fileinfo p = service.getImg(md5);
                                        imgsPpt.set(i, p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                                    }
                                } else if (imgsPpt.get(i) != null) {
                                    Map<String, String> resultMap = md5(imgsPpt.get(i));
                                    String md5 = resultMap.get("md5");
                                    String name = resultMap.get("name");
                                    imgsPpt.set(i, name + "?md5=" + md5);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    //保存欢迎界面
    @RequestMapping("/welcome_save")
    @ResponseBody
    public ApiClass welcomePageUpload(String id, String code, HttpServletRequest request) {
        ApiClass api = new ApiClass();
        //写文件
        File dir = new File(upload + "screen" + separator + id + separator + "welcome");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(upload + "screen" + separator + id + separator + "welcome" + separator + "welcome.json");
        OutputStreamWriter writer = null;
        try {

            JSONObject rootJson = JSONObject.parseObject(code);
           /* Map<String,String> resultMap = md5(bgBase64);
            String md5 = resultMap.get("md5");
            String name = resultMap.get("name");
            ((Map) ((Map) map.get("panel")).get("BG")).put("img", name + "?md5=" + md5);*/
            JSONObject bgJSON = rootJson.getJSONObject("panel").getJSONObject("BG");

            String mp3Json = bgJSON.getString("mp3"); //兼容老的
            if (mp3Json != null && mp3Json.length() > 0 && mp3Json.trim().startsWith("[")==false) {
                Map<String, String> resultMap = md5(mp3Json);
                String md5 = resultMap.get("md5");
                String name = resultMap.get("name");
                List<String> mp3SuccessList = new ArrayList();
                mp3SuccessList.add(name + "?md5=" + md5);
                bgJSON.put("mp3", name + mp3SuccessList);
                File file1 = new File(upload+"/"+name);
                if (file1.exists()){
                    ossUpload.upload(name, file1);
                }
            }
            else {
                List<String> mp3List = bgJSON.getObject("mp3", List.class);
                List<String> mp3SuccessList = new ArrayList();
                if (mp3List != null && mp3List.size() > 0) {
                    for (String mp3 : mp3List) {
                        Map<String, String> resultMap = md5(mp3);
                        String md5 = resultMap.get("md5");
                        String name = resultMap.get("name");
                        mp3SuccessList.add(name + "?md5=" + md5);
                        File file1 = new File(upload + "/" + name);
                        //./video/2020-07-27/98dc2b55afe44fe9b8f3939589f7bcfa.mp4
                        if (file1.exists()) {
                            ossUpload.upload(name, file1);
                        }
                    }
                    bgJSON.put("mp3", mp3SuccessList);
                }
            }

            //引导视屏
            //[{"delay":10,"type":"img","url":"./video/2020-11-16/88d45d267bee43309ccd71bee52d7d17.png"},{"delay":10,"type":"img","url":"./video/2020-11-16/a19790cfba004ec0b5f1b4dd74b6d2d4.png"}]
            JSONObject loadJSON = rootJson.getJSONObject("panel").getJSONObject("LEAD");
            if (loadJSON!=null){
                List loadVideos = loadJSON.getObject("videos",List.class);

                List<Object> videosSuccessList = new ArrayList();
                if (loadVideos!=null && loadVideos.size()>0){
                    for (Object  o:loadVideos){
                        if (o instanceof JSONObject)
                        {
                            JSONObject jsonObject = (JSONObject)o;
                            String video = jsonObject.getString("url");
                            Map<String, String> resultMap = md5(video);
                            String md5 = resultMap.get("md5");
                            String name = resultMap.get("name");
                            File file2 = new File(upload+"/"+name);
                            //./video/2020-07-27/98dc2b55afe44fe9b8f3939589f7bcfa.mp4
                            jsonObject.put("url",name + "?md5=" + md5);
                            videosSuccessList.add(jsonObject);
                            if (file2.exists()){
                                ossUpload.upload(name, file2);
                            }
                        }
                        else if (o instanceof String)
                        {
                            String video = (String)o;
                            Map<String, String> resultMap = md5(video);
                            String md5 = resultMap.get("md5");
                            String name = resultMap.get("name");
                            videosSuccessList.add(name + "?md5=" + md5);
                            File file2 = new File(upload+"/"+name);
                            //./video/2020-07-27/98dc2b55afe44fe9b8f3939589f7bcfa.mp4
                            if (file2.exists()){
                                ossUpload.upload(name, file2);
                            }
                        }


                    }
                    //System.out.println(videosSuccessList);
                    loadJSON.put("videos",videosSuccessList);
                }
            }





            String typeBg = bgJSON.getString("type");
            if ("video".equals(typeBg)) {
                String video = bgJSON.getString("video");
                if (video != null && video.length() > 0) {
                    Map<String, String> resultMap = md5(video);
                    String md5 = resultMap.get("md5");
                    String name = resultMap.get("name");
                    bgJSON.put("video", name + "?md5=" + md5);
                }
            } else if ("img".equals(typeBg)) {
                String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                String path = upload + "screen" + separator + "upload" + separator + date;
                JSONArray array = rootJson.getJSONObject("panel").getJSONObject("BG").getJSONArray("url");
                for (int i = 0; i < array.size(); i++) {
                    if (array.getString(i) != null && array.getString(i).startsWith("data:image/")) {
                        if (!new File(path).exists()) {
                            new File(path).mkdirs();
                        }
                        String suffix = array.getString(i).substring(11, array.getString(i).indexOf(";"));
                        String name = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                        //将md5图片转换成字节数组
                        //byte[] data = Base64.decode(imgs.get(i).substring(imgs.get(i).indexOf(",")+1)) ;
                        MessageDigest md5Digest = MessageDigest.getInstance("md5");
                        //对图片进行md5计算
                        byte[] digest = md5Digest.digest(array.getString(i).getBytes());
                        String md5 = HexUtil.encodeHexStr(digest);
                        if (!service.isExist(md5)) {
                            Fileinfo pictrul = new Fileinfo();
                            pictrul.setMd5(md5);
                            pictrul.setUrl("./screen/upload/" + date + "/" + name);
                            pictrul.setType("img");
                            Fileinfo p = service.addImg(pictrul);
                            File file2 = new File(path + separator + name);
                            Base64.decodeToFile(array.getString(i).substring(array.getString(i).indexOf(",") + 1), file2);
                            ossUpload.upload("/screen/upload/" + date + "/" + name, file2);
                            array.set(i, p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                        } else {
                            Fileinfo p = service.getImg(md5);
                            array.set(i, p.getUrl() + "?md5=" + MD5Util.md5sum(upload + p.getUrl()));
                        }
                    } else if (array.get(i) != null) {
                        Map<String, String> resultMap = md5(array.getString(i));
                        String md5 = resultMap.get("md5");
                        String name = resultMap.get("name");
                        array.set(i, name + "?md5=" + md5);
                    }
                }
            }

            //writer = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
            // writer.write("fun_id" + "('" + rootJson.toJSONString() + "')");
            //writer.close();


            //-----------------------------------------------------------------------------------------
            Theme theme = themeService.getById(id);

            //System.out.println("rootJSON:"+rootJson.toJSONString());
            String json = rootJson.toJSONString();
            json = json.replaceAll("\n","\\n");
            json = json.replaceAll("\r","\\r");

            //System.out.println("json:"+json);
            theme.setThemeWelcomePageAndroidunchecked(json);

            Admin admin = (Admin) request.getSession().getAttribute("admin");
            if (admin != null && admin.getAdminParent() != null && admin.getAdminParent() == 0) { //如果是管理员登录，这里要判断
                theme.setThemeWelcomePageAndroidchecked(json);//如果是管理员登录，这里要判断
                theme.setThemeWelcomePagePcchecked("fun_id" + "('" + json + "')");
                theme.setThemeWelcomePageStatus("审核通过");
            } else {
                Station station = (Station) request.getSession().getAttribute("station");
                if (admin == null && station == null) {
                    api.setCode(500);
                    api.setMsg("登录失效");
                    api.setData("");
                    return api;
                }
                theme.setThemeWelcomePageStatus("未审核");
            }



            theme.setThemeWelcomePagePcunchecked("fun_id" + "('" + json + "')");
            theme.setThemeWelcomePageAndroidunchecked(json);
            themeService.saveOrUpdate(theme);
            //-----------------------------------------------------------------------------------------


        } catch (Exception e) {
            e.printStackTrace();
            api.setCode(500);
            api.setMsg("存储失败");
            api.setData("");
            return api;
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return api;
    }


    /**
     * 上传数据之前进行md5验证，服务器已有的文件返回文件引用
     *
     * @param data
     * @return
     */
    @RequestMapping("/md5Check")
    @ResponseBody
    public ApiClass md5Check(String data) {
        Map<String, String> map = null;
        try {
            map = JSONObject.parseObject(data, Map.class);
        } catch (Exception e) {
            ApiClass api = new ApiClass();
            api.setCode(500);
            api.setMsg("数据异常");
            api.setData("");
            return api;
        }
        for (Map.Entry<String, String> temp : map.entrySet()) {
            Fileinfo pictrul = service.getImg(temp.getValue());
            if (pictrul != null) {
                File file = new File(upload + pictrul);
                if (file.exists() == false) {
                    service.delImageById(pictrul.getId());
                    map.put(temp.getKey(), "404");
                } else {
                    map.put(temp.getKey(), temp.getKey() + " = \"" + pictrul.getUrl() + "\"");
                }
            } else {
                map.put(temp.getKey(), "404");
            }
        }
        ApiClass api = new ApiClass();
        api.setCode(200);
        api.setMsg("验证结束,开始上传");
        api.setData(map);
        return api;
    }

    /**
     * @param data     界面数据
     * @param language 界面所对应的语言
     * @return 用于判断转换过程中是否报错
     * {
     * code:"" ,
     * msg:"" ,
     * data:{
     * "CN":{
     * "desktop":{
     * ...
     * }
     * } ,
     * "EN:{...}"
     * }
     * }
     */
    public ApiClass saveAsAndroidCode(String id, Map data, String language, HttpServletRequest request) {


        Map result = new HashMap();  //结果存储
        result.put("data", new HashMap());
        ((Map) result.get("data")).put("CN", new HashMap());
        ((Map) result.get("data")).put("EN", new HashMap());
        List lstServer = new ArrayList();
        lstServer.add(SERVER);
        ((Map) result.get("data")).put("SERVER", lstServer);

        //构造数据结构
        if (language != null && language.equals("CN")) {
            ((Map) ((Map) result.get("data")).get("CN")).put("desktop", new HashMap());

            decodeData(data, (Map) ((Map) ((Map) result.get("data")).get("CN")).get("desktop"));
        } else if (language != null && language.equals("EN")) {
            ((Map) ((Map) result.get("data")).get("EN")).put("desktop", new HashMap());

            decodeData(data, (Map) ((Map) ((Map) result.get("data")).get("EN")).get("desktop"));
        }

        result.put("code", "200");
        result.put("msg", "成功");

        //-----------------------------------------------------------------------------------------
        Theme theme = themeService.getById(id);

        String json = JSONObject.toJSONString(result);
        json = json.replaceAll("\n","\\n");
        json = json.replaceAll("\r","\\r");

        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if (admin != null && admin.getAdminParent() != null && admin.getAdminParent() == 0) { //如果是管理员登录，这里要判断

            if ("EN".equals(language)){
                theme.setEnglishAndroidYes(json);//如果是管理员登录，这里要判断
            }else{
                theme.setThemeAuditAndroidAudited(json);//如果是管理员登录，这里要判断
            }

        } else {

        }

        if ("EN".equals(language)){
            theme.setEnglishAndroidNo(json);
        }else{
            theme.setThemeAuditAndroidUnaudited(json);
        }


        themeService.saveOrUpdate(theme);
        //-----------------------------------------------------------------------------------------

        // writeToFile(id, upload + separator + "screen" + separator + id + separator + "android" + separator + "android.json", result, language, request);

        return null;
    }


    /**
     * 将source中的数据按照安卓中的格式转换到data中
     *
     * @param source 源数据
     * @param data   目标数据
     */
    public void decodeData(Map source, Map data) {
        Map content = (Map) ((Map) source).get("panel");


        //1.解析全局属性(颜色)
        //data.put("msg", "color,表示跑马灯和天气的颜色 , 组件中pos字段注解:pos表示组件所在的大概位置,t 顶部  , b 下部 , l 左 , r 右 , c 中间 , t-l 左上方 ...,有些参数可能未必有用，后续如果觉得哪个参数无效我再删了,内容组件在1080p分辨率下是以1658*620为面板设计的") ;
        data.put("color", content.get("color"));

        //解析背景图片
        data.put("bg", ((Map) content.get("BG")).get("img"));


        //2.解析logo
        if (content.get("VUELOGO") != null) {
            data.put("logo", new HashMap());
            ((Map) data.get("logo")).put("img", ((Map) content.get("VUELOGO")).get("img"));
            ((Map) data.get("logo")).put("pos", ((Map) content.get("VUELOGO")).get("pos"));
        }

        //3.解析天气组件
        if (content.get("VUECLOCK") != null) {
            data.put("clock", new HashMap());
            ((Map) data.get("clock")).put("pos", ((Map) content.get("VUECLOCK")).get("pos"));
        }

        //4.解析pmd组件
        if (content.get("VUEPMD") != null) {
            //System.out.println(content.get("VUEPMD"));
            data.put("pmd", new HashMap());
            ((Map) data.get("pmd")).put("pos", ((Map) content.get("VUEPMD")).get("pos"));
            ((Map) data.get("pmd")).put("dir", ((Map) content.get("VUEPMD")).get("dirction"));
            ((Map) data.get("pmd")).put("size", ((Map) content.get("VUEPMD")).get("size").toString());
            ((Map) data.get("pmd")).put("speed", ((Map) content.get("VUEPMD")).get("speed").toString());

            if (((Map) content.get("VUEPMD")).get("color") != null) {
                ((Map) data.get("pmd")).put("color", ((Map) content.get("VUEPMD")).get("color").toString());
            } else {
                ((Map) data.get("pmd")).put("color", "rgba(255,255,255,1)");
            }
            if (((Map) content.get("VUEPMD")).get("bkcolor") != null) {
                ((Map) data.get("pmd")).put("bkcolor", ((Map) content.get("VUEPMD")).get("bkcolor").toString());
            } else {
                ((Map) data.get("pmd")).put("bkcolor", "");
            }
            ((Map) data.get("pmd")).put("title", ((Map) content.get("VUEPMD")).get("title"));
            //((Map)data.get("pmd")).put("msg", "pos表示位置 , dir表示跑马灯方向(l向左，r向右) , size跑马灯字体大小(s小，m中，l大) , title跑马灯内容") ;
        }

        // 解析边角
        if (content.get("BORDER") != null) {
            data.put("border", new HashMap());
            ((Map) data.get("border")).put("type", ((Map) content.get("BORDER")).get("type"));
            ((Map) data.get("border")).put("color", ((Map) content.get("BORDER")).get("color"));
        }
        //关于我们
        if (content.get("ABOUT") != null) {
            data.put("about", new HashMap());
            ((Map) data.get("about")).put("type", ((Map) content.get("ABOUT")).get("type"));
            ((Map) data.get("about")).put("color", ((Map) content.get("ABOUT")).get("color"));
            ((Map) data.get("about")).put("img", ((Map) content.get("ABOUT")).get("img"));
            ((Map) data.get("about")).put("ppt", ((Map) content.get("ABOUT")).get("ppt"));
            ((Map) data.get("about")).put("text", ((Map) content.get("ABOUT")).get("text"));
            ((Map) data.get("about")).put("apk", pptURL);
        }

        if (content.get("VUELEFTPANEL") != null) {
            data.put("left_panel", new HashMap());
            ((Map) data.get("left_panel")).put("img", ((Map) content.get("VUELEFTPANEL")).get("img"));
        }

        //5.解析导航栏和内容组件
        if (content.get("MAIN") != null) {
            Map bar = (Map) content.get("MAIN");
            //当有导航栏时怎么处理
            data.put("main", new HashMap());
            //导航栏类型
            ((Map) data.get("main")).put("type", bar.get("type"));
            ((Map) data.get("main")).put("pos", bar.get("pos"));
            ((Map)data.get("main")).put("color" , bar.get("color")) ;
            ((Map)data.get("main")).put("selectColor" , bar.get("selectColor")) ;

            if (Boolean.parseBoolean(bar.get("bar").toString())) {
                ((Map) data.get("main")).put("exist", true);
            } else {
                ((Map) data.get("main")).put("exist", false);
            }
            List d = (List) bar.get("data");
            ((Map) data.get("main")).put("data", new ArrayList());
            for (int i = 0; i < d.size(); i++) {
                //便利每一个导航栏
                Map m = new HashMap();
                //获取导航栏图标地址
                String img = (String) ((Map) d.get(i)).get("img");
                String selectedImg = (String) ((Map) d.get(i)).get("selectedImg");
                String name = (String) ((Map) d.get(i)).get("name");
                m.put("icon", img);
                m.put("selectedIcon", selectedImg);
                m.put("name", name);
                if (((Map) d.get(i)).get("def") != null) {
                    m.put("defaultApk", ((Map) d.get(i)).get("defaultApk"));
                }
                //内容组件
                if(((Map) d.get(i)).get("subMenu") != null) {
                    m.put("submenu" , ((Map) d.get(i)).get("subMenu")) ;
                }
                if(((Map) ((Map) d.get(i)).get("data")).get("id") != null) {
                    ((Map) ((Map) d.get(i)).get("data")).put("layout", service.getLayout(((Map) ((Map) d.get(i)).get("data")).get("id").toString()));
                    m.put("content", ((Map) d.get(i)).get("data"));
                    ((List) ((Map) data.get("main")).get("data")).add(m);
                }
            }
        }
    }

    @GetMapping("/upload")
    public ApiClass err() {
        return new ApiClass(404, "非法请求", "");
    }

    //视频上传接口
    @PostMapping("/upload")
    @ResponseBody
    public ApiClass movieUpload(MultipartFile file) {
        if (file.isEmpty()) {
            return new ApiClass(500, "无数据", "");
        }

        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        FileOutputStream out = null;
        if (".mp4".equals(suffix) || ".avi".equals(suffix) || ".mp3".equals(suffix) || ".jpg".equals(suffix) || ".gif".equals(suffix) || ".jpeg".equals(suffix) || ".png".equals(suffix)) {
            String newFile = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            try {
                byte[] data = file.getBytes();
                MessageDigest md5Digest = MessageDigest.getInstance("md5");
                byte[] md5b = md5Digest.digest(data);
                String md5 = HexUtil.encodeHexStr(md5b);

                //验证一下文件是否存在
                if (service.isExist(md5)) {
                    return new ApiClass(200, "成功", service.getImg(md5).getUrl());
                }

                //存储区域
                String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                String path = upload + "video" + separator + date;

                if (!new File(path).exists()) {
                    new File(path).mkdirs();
                }

                out = new FileOutputStream(path + separator + newFile);
                out.write(data);
                out.close();

                Fileinfo video = new Fileinfo();
                video.setMd5(md5);
                video.setType("video");
                video.setUrl("./video/" + date + "/" + newFile);

                File file2 = new File(path + separator + newFile);
                ossUpload.upload("/video/" + date + "/" + newFile, file2);


                service.addImg(video);

                return new ApiClass(200, "成功", "./video/" + date + "/" + newFile);
            } catch (Exception e) {
                e.printStackTrace();
                return new ApiClass(500, "文件数据异常", "");
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return new ApiClass(500, "文件类型不支持", "");
    }


    /**
     * 加载桌面配置
     *
     * @param id
     * @param type
     * @return
     */
    @RequestMapping("/loadDeskConfig")
    @ResponseBody
    public String loadJson(String id, String type,String language) {
        Theme theme = themeService.getById(id);
        String json = null;
        if (type==null){
            type = "0";
        }
        if (theme != null) {
            switch (type){
                case "1":
                    if ("EN".equals(language)){
                        json = theme.getEnglishPcYes();
                    }else{
                        json =  theme.getThemeAuditPcAudited();
                    }
                    break;
                default:
                    if ("EN".equals(language)){
                        json = theme.getEnglishPcNo();
                    }else{
                        json =  theme.getThemeAuditPcUnaudited();
                    }
                    break;
            }

            if (json!=null){

                json = json.replaceAll("\\\\n","\\\\\\\\n");
                json = json.replaceAll("\\\\r","\\\\\\\\r");

            }
            //System.out.println(json);
            return json;
        }
        return "";
    }

    /**
     * 加载欢迎界面
     *
     * @param id   主题编号
     * @param type 1加载已审核  2.加载未审核
     * @return
     */
    @RequestMapping("/loadWelcomeConfig")
    @ResponseBody
    public String loadWelcomeConfig(String id, String type) {
        Theme theme = themeService.getById(id);
        String json = null;
        if (theme != null) {
            if ("1".equals(type)) {
                json =  theme.getThemeWelcomePagePcchecked();
            }
           else{
               json = theme.getThemeWelcomePagePcunchecked();
            }
            if (json!=null){
              /*  json = json.replaceAll("\\\\n","\\n");
                json = json.replaceAll("\\\\r","\\r");
                json = json.replaceAll("\n","\\n");
                json = json.replaceAll("\r","\\r");*/
                json = json.replaceAll("\\\\n","\\\\\\\\n");
                json = json.replaceAll("\\\\r","\\\\\\\\r");
            }
            return json;

        }

        return "";
    }


}
